﻿namespace Rialternative.DomainService
{
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.ServiceModel.DomainServices.Server;
    using Rialternative.Repositories;

    /// <summary>
    /// DomainService base class providing some basic methods.
    /// </summary>    
    public class RepositoryDomainService : DomainService
    {
        /// <summary>
        /// Gets or sets the repository.
        /// </summary>
        /// <value>The repository.</value>
        public virtual IRepository Repository { get; set; }

        /// <summary>
        /// Gets the current ChangeSet.
        /// </summary>
        /// <value>the changeSet.</value>
        [SuppressMessage("Microsoft.Usage", "CA2222:DoNotDecreaseInheritedMemberVisibility", Justification = "IRepository.Update() method needs access to the original ChangeSet. To be review in next release.")]
        internal new ChangeSet ChangeSet
        {
            get
            {
                return base.ChangeSet;
            }
        }

        /// <summary>
        /// OnError is called when unrecoverable error occurs.
        /// </summary>
        /// <param name="errorInfo">Informations about the current error.</param>
        protected override void OnError(DomainServiceErrorInfo errorInfo)
        {
            if (errorInfo != null && errorInfo.Error != null)
            {
                Trace.WriteLine(errorInfo.Error.Message, "Error");
            }

            base.OnError(errorInfo);
        }

        /// <summary>
        /// Disposes this <see cref="T:System.ServiceModel.DomainServices.Server.DomainService"/>.
        /// </summary>
        /// <param name="disposing">True if we're currently disposing.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.Repository.Dispose();
            }

            base.Dispose(disposing);
        }

        /// <summary>
        /// This method is called to finalize changes after all the operations in the current <see cref="P:System.ServiceModel.DomainServices.Server.DomainService.ChangeSet"/>
        /// have been invoked. This method should commit the changes as necessary to the data source.
        /// Any errors should be set on the individual <see cref="T:System.ServiceModel.DomainServices.Server.ChangeSetEntry"/>s in the <see cref="P:System.ServiceModel.DomainServices.Server.DomainService.ChangeSet"/>.
        /// </summary>
        /// <returns>
        /// True if the <see cref="P:System.ServiceModel.DomainServices.Server.DomainService.ChangeSet"/> was persisted successfully, false otherwise.
        /// </returns>
        protected override bool PersistChangeSet()
        {
            this.Repository.Persist();
            return base.PersistChangeSet();
        }
    }
}
